//
// Created by 28365 on 2025/3/13.
//

#include "../include/config/server_api/DefaultUpdaterAPI.h"
#include "../include/config/server_api/APIUrl.h"
#include "../include/utils/HttpUtils.hpp"

ReqValue<ValueData> DefaultUpdaterAPI::getConcurrencyCount(const ODUpdater &odUpdater) {
    ReqValue<ValueData> reqValue = HttpUtils::sendGet<ValueData>(APIUrl::MAX_DOWNLOAD_CONCURRENT,map<string,string>(),odUpdater);
    return reqValue;
}

ReqValue<string> DefaultUpdaterAPI::getResFile(const Res &res,int version, ofstream *outStream, const ODUpdater &odUpdater) {
    ReqValue<string> reqValue = HttpUtils::downloadFile(APIUrl::DOWNLOAD_RES + to_string(res.getId()),map<string,string>(),outStream,&res,version,odUpdater);
    return reqValue;
}

ReqValue<vector<int>> DefaultUpdaterAPI::getVersions(int nowVersion, int unpublishKey, const ODUpdater &odUpdater) {
    map<string,string> param;
    param["version"] = to_string(nowVersion);
    param["key"] = to_string(unpublishKey);
    ReqValue<vector<int>> reqValue = HttpUtils::sendGet<vector<int>>(APIUrl::VERSIONS,param,odUpdater);
    return reqValue;
}

ReqValue<vector<Res>> DefaultUpdaterAPI::getVersionRes(int version, int64_t labelId, int unpublishKey, const ODUpdater &odUpdater) {

    map<string,string> param;
    param["version"] = to_string(version);
    param["label"] = to_string(labelId);
    param["key"] = to_string(unpublishKey);

    ReqValue<vector<Res>> result;
    ReqValue<json> reqValue = HttpUtils::sendGet<json>(APIUrl::RES,param,odUpdater);

    for (const auto &item: reqValue.getData()){
        result.getData().emplace_back(item["resId"],item["path"],item["delete"]);
    }
    return result;
}

ReqValue<int> DefaultUpdaterAPI::getUnpublishedVersion(int unpublishKey, const ODUpdater &odUpdater) {
    ReqValue<int> reqValue;

    if (unpublishKey == 0){
        reqValue.setData(0);
        return reqValue;
    }

    map<string,string> param;
    param["key"] = to_string(unpublishKey);
    reqValue = HttpUtils::sendGet<int>(APIUrl::UNPUBLISHED_VERSION,param,odUpdater);
    return reqValue;
}

DefaultUpdaterAPI::~DefaultUpdaterAPI() = default;
